package svc

import (
	"github.com/bwmarrin/snowflake"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
	"mall/app/coupon/cmd/rpc/couponrpcservice"
	"mall/app/product/cmd/rpc/product"
	"mall/app/seckill/cmd/api/internal/config"
	"mall/app/seckill/cmd/api/internal/middleware"
)

type ServiceContext struct {
	Config           config.Config
	CouponRpcClient  couponrpcservice.CouponRpcService
	ProductRpcClient product.Product
	RedisClient      *redis.Redis
	AuthMiddleware   rest.Middleware
	IdGenerator      *snowflake.Node
}

func NewServiceContext(c config.Config) *ServiceContext {
	node, err := snowflake.NewNode(2)
	if err != nil {
		panic(err)
	}
	return &ServiceContext{
		Config:           c,
		CouponRpcClient:  couponrpcservice.NewCouponRpcService(zrpc.MustNewClient(c.CouponRpcClientConf)),
		ProductRpcClient: product.NewProduct(zrpc.MustNewClient(c.ProductRpcClientConf)),
		RedisClient: redis.New(c.Redis.Host, func(r *redis.Redis) {
			r.Type = c.Redis.Type
			r.Pass = c.Redis.Pass
		}),
		AuthMiddleware: middleware.NewAuthMiddleware().Handle,
		IdGenerator:    node,
	}
}
